<template>
  <div style="position: relative;" >
    <loading></loading>
    <error></error>
      <div class="g-legend-wrapper top">
      <span class="g-legend-title g-font-f4">{{option.accTitle}}
        <span class="g-font-f5">{{updateTime}}</span>
      </span>
        <div class="g-legend-content">
        <span class="g-font-f5 g-legend-item" :class="NetNum>0?'red':'green'">
          {{NetNum>0?option.accPositiveText:option.accNegativeText}}
          <span class="number">{{NetNum | numOfLg}}</span>{{NetNum | textOfLg}}
        </span>
          <span class="g-font-f5 g-legend-item blue">
          {{IndexText}}
          <span class="number">{{IndexNum}}</span>
        </span>
        </div>
      </div>

      <div ref="chartLine" class="chart-line" id="splitLine">
      </div>

      <div class="g-legend-wrapper bottom">
      <span class="g-legend-title g-font-f4">{{option.mTitle}}
      </span>
        <div class="g-legend-content">
        <span class="g-font-f5 g-legend-item more" :class="MNetNum>0?'red':'green'">
          {{MNetNum>0?option.mNetPositiveText:option.mNetNegativeText}}
          <span class="number">{{MNetNum | numOfLg}}</span>{{MNetNum | textOfLg}}
        </span>
          <span class="g-font-f5 g-legend-item red-light">
          {{option.mPositiveText}}
          <span class="number">{{MGainNum | numOfLg}}</span>{{MGainNum | textOfLg}}
        </span>
          <span class="g-font-f5 g-legend-item green-light">
          {{option.mNegativeText}}
          <span class="number">{{MSlipNum | numOfLg}}</span>{{MSlipNum | textOfLg}}
        </span>
        </div>
      </div>

      <div ref="chartBar" class="chart-bar">
      </div>
  </div>
</template>

<script>
  import echarts from 'echarts/lib/echarts';
  import { getTradeTimeArr, max, min, getIndexMaxChg } from '@/common/common'
  import { dataTimeFormat4 } from '@/filters/dataTime'
  import { mapGetters } from 'vuex';
  import { numOfLg, textOfLg } from '@/filters/legendFormat'

  const tradeDateArr = getTradeTimeArr();
  let chgRng = 2;      // 设百分比为2
  let closing = 0;

  const option = {
    grid: {
      x: '0',
      y: '8',
      width: '100%',
      height: '90%'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: tradeDateArr,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dot',
          color: '#bac9d8'
        },
        interval: 59
      },
      axisLabel: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: 'rgb(186,201,216)',
          type: 'dot'
        }
      },
      axisPointer: {
        show: true,
        type: 'line',
        lineStyle: {
          color: '#212138',
          type: 'solid'
        },
        label: {
          show: false,
          backgroundColor: 'transparent',
          textStyle: {
            color: 'transparent'
          }
        }
      },
      splitNumber: 4,
      axisTick: {
        show: false
      }
    },
    yAxis: [
      {
        z: 999,
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dotted',
            color: '#bac9d8'
          }
        },
        axisLine: {
          show: false
        },
        axisLabel: {
          textStyle: {
            color: '#999'
          },
          inside: true
        }
      },
      {
        z: 999,
        splitLine: {
          show: false
        },
        axisLabel: {
          inside: true,
          textStyle: {
            color: '#999'
          }
        },
        position: 'right',
        type: 'value'
      }],
    series: [
      {
        name: '净流入流出',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        showSymbol: false,
        yAxisIndex: 0
      },
      {
        name: '证券指数',
        type: 'line',
        symbol: 'none',
        smooth: true,
        yAxisIndex: 1,
        lineStyle: {
          normal: {
            width: 1.5,
            color: '#6c9bd2',
            type: 'dotted'
          }
        }
      }
    ]
  };

  const optionBar = {
    grid: {
      x: '0', y: '0', y2: '20px', width: '100%', height: '70%'
    },
    tooltip: {
      trigger: 'axis',
      showContent: false
    },
    xAxis: {
      boundaryGap: false,
      data: tradeDateArr,
      axisLabel: {
        textStyle: {
          color: '#a5a5a5',
          align: 'center'
        },
        interval: 59,
        formatter: (val, index) => {
          if (index == 0) {
            return '          ' + val;
          } else if (index == tradeDateArr.length - 1) {
            return val + '           ';
          } else if (index == 120) {
            return val
          }
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dot',
          color: '#bac9d8'
        },
        interval: 59
      },
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          type: 'dotted',
          color: '#bac9d8'
        }
      },
      axisPointer: {
        show: true,
        type: 'line',
        lineStyle: {
          color: '#212138',
          type: 'solid'
        },
        label: {
          show: false,
          backgroundColor: 'transparent',
          textStyle: {
            color: 'transparent'
          }
        }
      },
      min: 0,
      max: 240
    },
    yAxis: {
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dot',
          color: '#bac9d8'
        }
      },
      splitNumber: 1,
      axisLine: {
        show: false
      }
    },
    series: [
      {
        name: '净流入流出',
        type: 'bar',
        stack: 'one',
        itemStyle: {
          normal: {
            color: (params) => params.data > 0 ? '#e84b4b' : '#2cc05c'
          }
        }
      },
      {
        name: '流入',
        type: 'bar',
        stack: 'one',
        itemStyle: {
          normal: {
            color: '#f7b8b8'
          }
        }
      },
      {
        name: '流出',
        type: 'bar',
        stack: 'one',
        itemStyle: {
          normal: {
            color: '#ade7bf'
          }
        }
      }
    ]
  };

  export default {
    name: 'chart-connect',
    data () {
      return {
        tmpData: null,
        updateTime: '',
        dataIndex: ''
      }
    },
    props: {
      aid: {
        default: () => {
          return 0
        }
      },
      option: {
        type: Object,
        default: function () {
          return {
            accTitle: '累计净流入流出',
            accPositiveText: '净流入',
            accNegativeText: '净流出',
            mTitle: '分钟流入流出',
            mNetPositiveText: '净流入',
            mNetNegativeText: '净流出',
            mPositiveText: '流入',
            mNegativeText: '流出'
          }
        }
      },
      chartData: { // 数据
        type: Object,
        default: function () {
          return {
            xTime: [],
            netNumber: [],
            minute: {
              in: [],
              out: []
            },
            indexData: {}
          }
        }
      }
    },
    watch: {
      chartData: function (val) {
        console.log(val)
        closing = val.indexData.closing;
        chgRng = getIndexMaxChg(val.indexData);

//        if (this.transitProgress == 'end')
        this.renderChart();
      }
//      transitProgress(val) {
//        if (val == 'end' && this.chartData.indexData) {
//          alert('进场结束!');
//          this.renderChart();
//        }
//      }
    },
    filters: {
      dataTimeFormat4,
      numOfLg,
      textOfLg,
      nan (num) {
        return isNaN(num) ? '' : ''
      }
    },
    computed: {
      ...mapGetters(
        ['transitProgress']
      ),
      IndexText() {
        return ['上证指数', '上证指数', '深证指数', '创业板'][this.aid];
      },
      NetNum() {
        return this.chartData.netNumber ? this.chartData.netNumber[this.dataIndex] : '';
      },
      IndexNum() {
        return this.chartData.indexData ? this.chartData.indexData.index[this.dataIndex] : '';
      },
      MNetNum() {
        return this.chartData.minute ? this.chartData.minute.mNetNumber[this.dataIndex] : '';
      },
      MGainNum() {
        return this.chartData.minute ? this.chartData.minute.in[this.dataIndex] : '';
      },
      MSlipNum() {
        return this.chartData.minute ? this.chartData.minute.out[this.dataIndex] : '';
      }
    },
    methods: {
      chartSelected(params) {
        this.dataIndex = params[0].dataIndex;
        this.updateTime = params[0].axisValue;
      },

      renderChart () {
        Promise
          .all([this.chartBarPromise(), this.chartLinePromise()])
          .then(res => {
            if (res.length != 2) return;
            this.$store.dispatch('hideLoading');                // 图表渲染成功    loading或Error消失
            this.$store.dispatch('hideError');
          })
      },

      chartBarPromise() {
        return new Promise((resolve, reject) => {
          this.chartBar.setOption({
            series: [{
              data: this.chartData.minute.mNetNumber
            }, {
              data: this.chartData.minute.in
            }, {
              data: this.chartData.minute.out
            }]
          });
          setTimeout(() => {
            resolve()
          }, 0)
        });
      },

      chartLinePromise() {
        const maxNum = max(this.chartData.netNumber);
        const minNum = min(this.chartData.netNumber);
        const INTERVAL = max([Math.abs(maxNum), Math.abs(minNum)]);

        const ratio = maxNum < 0 ? 0
          : minNum > 0 ? 1
          : maxNum / (maxNum + Math.abs(minNum));

        return new Promise((resolve, reject) => {
          this.chartLine.setOption({
            yAxis: [{
              max: (INTERVAL * 1.2).toFixed(2),
              min: -(INTERVAL * 1.2).toFixed(2),
//              splitNumber: 2,
              interval: INTERVAL * 1.2 / 8,
              axisLabel: {
                formatter: (value, index) => {
                  if (index == 1 || index == 15) {
                    return `${numOfLg(INTERVAL * 1.2)}${textOfLg(INTERVAL * 1.2)}`
                  } else if (index == 8) {
                    return 0
                  } else {
                    return null
                  }
                }
              }
            }, {
              axisLabel: {
                formatter: (value, index) => {
                  let cptYAxisLabel = pm => (closing / 100 * (pm * chgRng + 100)).toFixed(0) + '(' + (pm * chgRng) + '%)';
                  if (index == 1) {
                    return cptYAxisLabel(-1)
                  } else if (index == 8) {
                    return cptYAxisLabel(0)
                  } else if (index == 15) {
                    return cptYAxisLabel(1)
                  }
                }
              },
              min: -chgRng,
              max: chgRng,
              interval: chgRng / 8
            }],
            series: [{
              data: this.chartData.netNumber,
              yAxisIndex: 0,
              lineStyle: {
                normal: {
                  width: 1,
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: '#eb333b'
                    }, {
                      offset: ratio, color: '#eb333b'
                    }, {
                      offset: ratio, color: '#1aae52'
                    }, {
                      offset: 1, color: '#1aae52'
                    }],
                    globalCoord: false // 缺省为 false
                  }
                }
              },
              areaStyle: {
                normal: {
                  color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                      offset: 0, color: 'rgba(226, 70, 70, 0.2)'
                    }, {
                      offset: ratio, color: 'rgba(226, 70, 70, 0.2)'
                    }, {
                      offset: ratio, color: 'rgba(26, 174, 82, 0.2)'
                    }, {
                      offset: 1, color: 'rgba(26, 174, 82, 0.2)'
                    }],
                    globalCoord: false
                  }
                }
              }
            }, {
              data: this.chartData.indexData.index.map(v => (v - closing) / closing * 100)
            }],
            tooltip: {
              formatter: this.chartSelected
            }
          });
          setTimeout(() => {
            resolve()
          }, 0)
        });
      }
    },
    mounted () {
      this.$store.dispatch('showLoading');
      this.chartLine = echarts.init(this.$refs.chartLine);
      this.chartLine.setOption(option);
      this.chartBar = echarts.init(this.$refs.chartBar);
      this.chartBar.setOption(optionBar);

      echarts.connect([this.chartLine, this.chartBar]);
    },
    beforeDestroy () {
      echarts.dispose(this.chartLine);
      echarts.dispose(this.chartBar);
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
  #splitLine{
    background-image:
      -webkit-linear-gradient(left,#ddd,#ddd 2px),
      -webkit-linear-gradient(left,#bac9d8,#bac9d8 2px,transparent 2px,transparent 3px),
      -webkit-linear-gradient(left,#bac9d8,#bac9d8 2px,transparent 2px,transparent 3px),
      -webkit-linear-gradient(left,#ddd,#ddd 2px) !important;
    background-size: 3px 1px !important;
    background-position: 0 0,0 25%,0 75%,0 100% !important;
    background-repeat: repeat-x !important;
  }
  .chart-line {
    width: 100%;
    height: 1.3rem;
  }
  .chart-bar {
    width: 100%;
    height: .935rem;
  }
  .top{
    padding: .02rem 0;
    .g-legend-title{
      text-align: left;
      margin-left: 0.10rem;
    }
    .g-legend-content{
      padding: 0 .15rem 0 .225rem;
      .g-legend-item {
        width: 50%;
        white-space: nowrap;
      }
    }
  }
  .bottom{
    line-height: .3rem;
    .g-legend-content {
      padding-left: 0.05rem;
      margin-left: 0.10rem;
      .g-legend-item{
        white-space: nowrap;
        width: 32%;
        &.more {
          width: 36%
        }
      }
    }
  }
</style>
